package com.ruge.core.exception;

import com.ruge.core.response.Response;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author ruge.wu
 * @since 2022/1/5 10:20
 */
@RestController
public class SpringBootErrorController implements ErrorController {

    /**
     * 获取HTTP请求状态码
     */
    public HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }

    /**
     * 处理Ajax请求的错误
     *
     * @param request  {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/error")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpStatus status = getStatus(request);
        Response errorBody = new Response();
        errorBody.setStatus(Response.Status.FAILED);
        errorBody.setErrorCode("SYS." + status.value());
        errorBody.setErrorMessage(status.getReasonPhrase());
        return new ResponseEntity(errorBody, status);

    }

}
